//
//  UICopyLabel.swift
//  QingLiuSwift
//
//  Created by xyanl on 2024/4/19.
//  Copyright © 2024 考拉🐨. All rights reserved.
//
//  可以复制的label
import UIKit

class UICopyLabel: UILabel {
    override init(frame: CGRect) {
        super.init(frame: frame)
        sharedInit()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        sharedInit()
    }
    
    func sharedInit() {
        isUserInteractionEnabled = true
        addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(showMenu(_:))))
    }
    
    @objc func showMenu(_ sender: UILongPressGestureRecognizer) {
        becomeFirstResponder()
        let menu = UIMenuController.shared
        if !menu.isMenuVisible {
            menu.showMenu(from: self, rect: bounds)
        }
    }
    
    // 复制
    override func copy(_ sender: Any?) {
        let board = UIPasteboard.general
        board.string = text
        let menu = UIMenuController.shared
        menu.hideMenu()
    }
    
    override func paste(_ sender: Any?) {
        // 粘贴
        let board = UIPasteboard.general
        text = board.string
        let menu = UIMenuController.shared
        menu.hideMenu()
    }
    
    override func select(_ sender: Any?) {
        // 选择
    }
    
    override func delete(_ sender: Any?) {
        // 删除
    }
    
    // 使视图具有响应性
    override var canBecomeFirstResponder: Bool {
        return true
    }
    
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        // 复制
        if action == #selector(UIResponderStandardEditActions.copy(_:)) {
            return true
        }
        
        // 粘贴
        if action == #selector(UIResponderStandardEditActions.paste(_:)) {
            // return true
        }
        return false
    }
}

